<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Admin\CommonController;
use App\Models\BookTypes;
use App\Models\District;
use Illuminate\Support\Facades\Cache;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

/**
 * 公共的一些数据
 */
class TextController extends Controller
{

    public $commonObj = null;
    public function __construct()
    {
        $this->commonObj = new CommonController();
    }

    /**
     * 书籍类型筛选列表(用于下拉框选择)
     */
    public function bookTypesFilterList()
    {
        $bookTypesObj = new BookTypes();
        $res = $bookTypesObj->select('id', 'title')->where('level', 1)->orderBy('id')->get();


        if ($res->isEmpty()) {
            return $this->commonObj->returnApi(203, "暂无数据");
        }
        return $this->commonObj->returnApi(200, "获取成功", true, $res->toArray());
    }

    /**
     * 获取学历筛选列表
     */
    public function educationFilterList()
    {
        $data = Controller::educationName();
        return $this->commonObj->returnApi(200, "获取成功", true, $data);
    }



    /**
     * 获取城市文件,组装数据，返回省、市、(区、县)、街道
     * @param is_letter  是否需要首字母  1 需要  2 不需要（默认不需要，可不传此参数）
     * @param parent_id 父级id
     * @param is_tree 是否返回省市区三级树形结构  1是 2否    属性结构只能返回 3 级，若需要街道，获取到省市区后，在根据父级id，获取街道
     */
    public function getCityAll()
    {
        $is_letter = request()->is_letter ? request()->is_letter : 2;
        $parent_id = request()->parent_id ? request()->parent_id : 0;
        $is_tree = request()->is_tree ? request()->is_tree : 1;

        $district_model = new District();

        if ($is_tree == 1) {
            $cahce = Cache::get('district');

            if ($cahce) {
                return $this->returnApi(200, '获取成功', true, $cahce);
            }

            $res = $district_model->select('id', 'parent_id as pid', 'name', 'level', DB::raw("if(name = '宜宾市' or name = '四川省',0,1) as order_num"))
                ->where('level', '<=', 3)
                ->orderBy('order_num')
                ->get()
                ->toArray();

            if ($is_letter == 1) {
                $data = [];
                foreach ($res as $key => $value) {
                    $data[$key]['first_letter'] = get_first_charter($value['name']); //按字母排序
                    $data[$key]['id'] = $value['id'];
                    $data[$key]['pid'] = $value['pid'];
                    $data[$key]['name'] = $value['name'];
                    $data[$key]['level'] = $value['level'];
                }
                sort($data);
                $res = $data; //重新赋值给$res
            }

            $temp = [];
            foreach ($res as $key => $value) {
                if ($value['level'] == 1) {
                    $temp[] = $this->getTree($value, $res);
                }
            }

            Cache::put('district', $temp, 24 * 60 * 60 * 3); //缓存3天
            $res = $temp;
        } else {

            // $res = $district_model->field('id,parent_id as pid,name,level,if(name = "重庆" or name = "渝中区",0,1) as order_num')->where('parent_id',$parent_id);
            $res = $district_model->select('id', 'parent_id as pid', 'name', 'level', DB::raw("if(name = '宜宾市' or name = '四川省',0,1) as order_num"))->where('parent_id', $parent_id);

            /**只显示主城区 */
            // if($parent_id == 609){
            //     $array = ['渝中区','江北区', '南岸区' , '九龙坡区' , '沙坪坝区' , '大渡口区' , '北碚区' , '渝北区' , '巴南区'];

            //     $res = $res->where('name','in',$array);
            // }

            $res = $res
                ->orderBy('order_num')
                // ->orderByDesc('id')
                ->get();

            if ($res->isEmpty()) {
                return $this->returnApi(203, '暂无数据');
            }

            $res = $res->toArray();
            /**优先排序 */
            if ($is_letter == 1) {
                $data = [];
                foreach ($res as $key => $value) {
                    $data[$key]['first_letter'] = get_first_charter($value['name']);
                    $data[$key]['id'] = $value['id'];
                    $data[$key]['pid'] = $value['pid'];
                    $data[$key]['name'] = $value['name'];
                    $data[$key]['level'] = $value['level'];
                    // unset($res[$key]['order_num']);
                }
                sort($data);

                $res = $data; //重新赋值给$res
            }
        }
        return $this->returnApi(200, '获取成功', true, $res);
    }

    /**
     * 清除缓存
     */
    public function clearCache()
    {
        Cache::rm('district');
    }

    /**递归 */
    function getTree($arr, $menu)
    {
        if (!$arr['pid']) {
            $arr['children'] = [];
        }

        foreach ($menu as $key => $value) {
            if ($arr['id'] == $value['pid']) {
                $temp = [];
                $temp = $this->getTree($value, $menu);
                if ($temp) {
                    $arr['children'][] = $temp;
                }
            }
        }

        return $arr;
    }
}
